<template>
  <div class="el" >
    <el-tabs tab-position="left" v-model="options.tab.activateName">
    <el-tab-pane label="普查标题" name="investTitle">
      <el-row class="select-list">
        <h4 class="greenFontColor">通用普查表设计</h4>
      </el-row>
      <el-row class="select-list" v-permission="'bus:structure:save'">
  
        <el-form :inline="true" ref="structureForm" :model="models.structure" label-position="left"
                  size="mini" @submit.native.prevent label-width="100px" >
          <el-form-item label="调查类别" prop="categoryId">
            <el-tree-select v-model="models.structure.categoryId" :selectParams="options.tree.category.selectParams"
                    :treeParams="options.tree.treeParams"
                    @searchFun="searchCategoryFun" ref="categoryTreeSelect"  style="width: 500px" :teleported="true"/>
          </el-form-item>
          <br/>
          <el-form-item label="年月" prop="monthId" >
            <el-date-picker v-model="models.structure.monthId" value-format="yyyyMM" format="yyyy 年 MM 月" type="month" style="width: 250px"  placeholder="选择年月"/>
          </el-form-item>
          <br/>
          <el-form-item label="标题" prop="title" style="width: 100%">
            <el-input v-model="models.structure.title" placeholder="标题" size="small" style="width: 500px" clearable/>
          </el-form-item>
          <br/>
          <el-form-item label="副标题" prop="subTitle" style="width: 100%">
            <el-input v-model="models.structure.subTitle" placeholder="副标题" size="small" style="width: 500px" clearable/>
          </el-form-item>
          <br/>
          <el-form-item label="状态" prop="status">
            <el-switch v-model="models.structure.status" active-color="#13ce66" inactive-color="#ff4949"
                      active-text="正常"
                      inactive-text="停用"
                      active-value="0"
                      inactive-value="1">
            </el-switch>
        </el-form-item>
          <div>
              <el-button type="primary" plain @click="submitStructureForm" size="medium" style="float:left">确 定</el-button>
          </div>
        </el-form>
    </el-row>
    </el-tab-pane>
    <el-tab-pane label="通用附表" :disabled="options.tab.commonDisabled" name="commonTab" ref="commonSubTable">
      <el-row class="select-list">
        <h4 class="greenFontColor">通用普查表设计-通用附表设计</h4>
      </el-row>
      <el-row class="select-list" v-permission="'bus:structure:save'">
        <el-form :inline="true"  ref="commonStructureForm" :model="models.common" label-position="left"
        size="mini" @submit.native.prevent label-width="100px" >
            <el-form-item label="标题" prop="title" style="width: 100%">
              <el-input v-model="models.common.title" placeholder="标题" size="small" style="width: 500px" clearable/>
            </el-form-item>
            <br/>
            <el-form-item label="前置选项" prop="headCode" style="width: 100%">
              <sub-table-prop :options="options.common.head"  @change="commonHeadCodeHandlerCheckedChange"/>
            </el-form-item>
            <sub-table :subStructureId="models.common.id" @handleEvent="commSubStructureHandler"></sub-table>
            <el-form-item label="后置选项" prop="headCode" style="width: 100%">
              <sub-table-prop :options="options.common.end"  @change="commonEndCodeHandlerCheckedChange"/>
            </el-form-item>
            <div>
              <el-button type="primary" plain @click="submitSubStructureForm" size="medium" style="float:left">确 定</el-button>
            </div>
        </el-form>
      </el-row>
    </el-tab-pane>
    <el-tab-pane label="自定义附表" :disabled="options.tab.userDefineDisabled" name="userDefinedTab1">
      <el-row class="select-list">
        <h4 class="greenFontColor">通用普查表设计-自定义附表设计（用来设计文本字段）</h4>
      </el-row>
      <el-row class="select-list" v-permission="'bus:structure:save'">
        <el-form :inline="true"  ref="userDefineForm" :model="models.dynamic" label-position="left"
        size="mini" @submit.native.prevent label-width="100px" >
            <el-form-item label="标题" prop="title" style="width: 100%">
              <el-input v-model="models.dynamic.title" placeholder="标题" size="small" style="width: 500px" clearable/>
            </el-form-item>
            <br/>
            <el-form-item label="前置选项" prop="headCode" style="width: 100%">
              <sub-table-prop :options="options.dynamic.head"  @change="userDefineHeadCodeHandlerCheckedChange"/>
            </el-form-item>
             <el-form-item label="动态标题设置" prop="title" style="width: 100%">
              <el-input v-model="models.dynamic.titleDefine" placeholder="请用|隔开" size="large" style="width: 500px" type="textarea" clearable/>
              &nbsp;&nbsp;<el-button type="primary" plain @click="buildTable" size="medium">生成表格</el-button>
            </el-form-item>
            <dynamic-table :userDefineColumns="models.dynamic.titleDefineColumns" 
              v-show="models.dynamic.titleDefine && models.dynamic.titleDefine !==''" 
              :subStructureId="models.dynamic.id" @handleEvent="dynamicSubStructureHandler"></dynamic-table>
            <el-form-item label="后置选项" prop="headCode" style="width: 100%">
              <sub-table-prop :options="options.dynamic.end"  @change="userDefineEndCodeHandlerCheckedChange"/>
            </el-form-item>
            <div>
              <el-button type="primary" plain @click="submitUserDefineForm" size="medium" style="float:left">确 定</el-button>
            </div>
        </el-form>
      </el-row>
    </el-tab-pane>
    <el-tab-pane label="自定义附表" :disabled="options.tab.userDefineDisabled" name="userDefinedTab2">

    </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script lang="ts">
import {Component, Ref, Vue} from 'vue-property-decorator';
import {categoryTreeSelectData} from '@/api/investCategory';
import SubTableProp from '@/components/SubTableProp.vue';
import SubTable from '@/components/SubTable.vue';
import DynamicTable from '@/components/DynamicTable.vue';
import { categoryData } from '@/api/investCode';
import router from '@/router/index';
import { addStructure,updateStructure,getStructureById } from '@/api/investStructure';
import { addSubStructureJson,updateSubStructure,queryByStructureId} from '@/api/investSubStructure';

@Component({components:{SubTableProp,SubTable,DynamicTable}})
export default class Structure extends Vue {

  @Ref('categoryTreeSelect') private categoryTreeSelect: any;
  @Ref('structureForm') private structureForm;
  @Ref('commonSubTable') private commonSubTable;
  @Ref('commonStructureForm') private commonStructureForm;
  @Ref('userDefineForm') private userDefineForm;
  
  models:any ={
    structure:{
      categoryId: '',
      title:'',
      subTitle: '',
      monthId: '',
      id:'',
      status:'0'
    },
    common:{
      headCode:'',
      title:'',
      endCode:'',
      gridCategory:'common',
      id:'',
      status:'0',
      structureId:'',
      commonDataList:[]
    },
    dynamic:{
      headCode:'',
      endCode:'',
      title:'',
      status:'0',
      titleDefine:'',
      titleDefineColumns:[],
      gridCategory:'',
      id:'',
      structureId:'',
      dynamicDataList:[]
    }
  }

  options:any={
    common:{
      data:[],
      //前置属性，数据和已选
      head:{
        data:[],
        checkedValues:[]
      },
      //后置属性，数据和已选
      end:{
        data:[],
        checkedValues:[]
      }
    },
    dynamic:{
      data:[],
      //前置属性，数据和已选
      head:{
        data:[],
        checkedValues:[]
      },
      //后置属性，数据和已选
      end:{
        data:[],
        checkedValues:[]
      }
    },
    tree:{
      category:{
        selectParams: {
          clearable: true,
          placeholder: '请选择类别'
        }
      },
      treeParams: {
        clickParent: true,
        filterable: true,
        accordion: true,
        data: [],
        props: {
          children: 'children',
          label: 'label',
          disabled: 'disabled',
          value: 'id'
        }
      }
    },
    tab:{
      editableTabsValue: '2',
      commonDisabled: true,
      userDefineDisabled: true,
      activateName:'investTitle',
      editableTabs: [{
        title: '标题信息',
        name: '标题信息',
        id: '1'
      }, {
        title: '通用附表信息',
        name: '通用附表信息',
        id: '2'
      }],
      tabIndex: 2
    }
  }

  buildTable(){ 
    console.log("表数据为：",this.models.dynamic.titleDefine)
    if(this.models.dynamic.titleDefine){
      this.models.dynamic.titleDefineColumns = [];
      const genArr = this.generateSequence(20,'code');
      this.models.dynamic.titleDefine.split('|').forEach((val:any,index:any) =>{
        if(!val){
          return;
        }
        this.models.dynamic.titleDefineColumns.push({'code':genArr[index],'name':val.trim()});
      })
    }
  }


 generateSequence =(length: number,pre: string): string[] => {
  return Array.from({ length: length }, (_, i) => {
    const number = i + 1;
    const prefix = (number > 9 ? '' : '0');
    return pre+ prefix + number.toString();
  });
}

  searchCategoryFun(value: any): void {
    this.categoryTreeSelect.filterFun(value);
  }

  submitStructureForm(): void{
    this.structureForm.validate((valid: boolean) => {
      //结构表验证成功
      if (valid) {
        //有标识是需要更新的
        if(this.models.structure.id){
          updateStructure(this.models.structure).then((response: any) => {
            this.$message.success(response.msg);
          }).catch((e) => {
            console.error(e);
            this.$message.error('调查结构表单更新失败');
          });
        }else{
        //没有标识就是保存
          addStructure(this.models.structure).then((response: any) => {
            this.models.structure.id= response.data;
            this.models.common.structureId =   this.models.structure.id;
            this.models.dynamic.structureId = this.models.structure.id;
            this.$message.success(response.msg);
            this.options.tab.commonDisabled = false;
            this.options.tab.activateName ='commonTab'
          }).catch((e) => {
            console.error(e);
            this.$message.error('调查结构表单新增失败');
          });
        }
     
      }
    });
  }

  submitSubStructureForm():void{
    this.commonStructureForm.validate((valid: boolean) => {
      //首先验证
      if (valid) {
        //有标识就是更新
        if(this.models.common.id){
            const model = {...this.models.common};
            delete model.commonDataList;
            updateSubStructure(model).then((response:any) => {
              this.$message.success(response.msg);
            }).catch(error => {
            // 处理错误
              console.error(error);
              this.$message.error('调查结构附表更新失败');
            });
         
          }else{
    
            addSubStructureJson(this.models.common).then(res => {
              let dt = JSON.parse(JSON.stringify(res.data));
              this.models.common.id= dt.data;
              this.options.tab.userDefineDisabled = false;
              this.$message.success(dt.msg);
              }).catch(error => {
                // 处理错误
                console.error(error);
                this.$message.error('调查结构附表新增失败');
              });
          }
        }
    });
  }

  submitUserDefineForm(){
    this.userDefineForm.validate((valid: boolean) => {
      //首先验证
      if (valid) {
        //有标识就是更新
        if(this.models.dynamic.id){
            const model = {...this.models.dynamic};
            delete model.dynamicDataList;
            model.gridCategory = JSON.stringify(model.titleDefineColumns) +'';
            updateSubStructure(model).then((response:any) => {
              this.$message.success(response.msg);
            }).catch(error => {
            // 处理错误
              console.error(error);
              this.$message.error('调查结构附表更新失败');
            });
         
          }else{
            this.models.dynamic.gridTitle= JSON.stringify(this.models.dynamic.titleDefineColumns) +'';
            
            addSubStructureJson(this.models.dynamic).then(res => {
              let dt = JSON.parse(JSON.stringify(res.data));
              this.models.dynamic.id= dt.data;
              this.options.tab.userDefineDisabled = false;
              this.$message.success(dt.msg);
              }).catch(error => {
                // 处理错误
                console.error(error);
                this.$message.error('调查结构自定义附表新增失败');
              });
          }
        }
    });
  }

  buildCategoryData(){
    categoryTreeSelectData().then((response: any) => {
      if (response.data) {
        this.options.tree.treeParams.data = response.data;
        if(this.categoryTreeSelect){
          this.categoryTreeSelect.treeDataUpdateFun(response.data);
        }
      }
    }).catch((e) => {
      console.error(e);
    });

    categoryData({'category':"附表前置字段"}).then((response: any) => {
      if (response.data) {
        this.options.common.head.data = response.data;
        this.options.dynamic.head.data = response.data;
      }
    }).catch((e) => {
      console.error(e);
    });

    categoryData({'category':"附表后置字段"}).then((response: any) => {
      if (response.data) {
        this.options.common.end.data= response.data;
        this.options.dynamic.end.data = response.data;
      }
    }).catch((e) => {
      console.error(e);
    });

    const rowId = router.currentRoute.query.id;
    if(rowId){
        this.options.tab.commonDisabled = false;
        this.options.tab.userDefineDisabled= false;
        this.models.structure.id = rowId;
        getStructureById({id:rowId}).then(res =>{
          if(res.data){
            this.models.structure.title = res.data && res.data.title;
            this.models.structure.subTitle = res.data && res.data.subTitle;
            this.models.structure.categoryId = res.data && res.data.categoryId;
            this.models.structure.status = res.data && res.data.status;
            this.models.structure.monthId = res.data.monthId + '';
            this.models.common.structureId = rowId;
            this.models.dynamic.structureId = rowId;
          }
        }).catch((e) => {
          console.error(e);
      });
      queryByStructureId({id:rowId}).then(res =>{
        if(res.data){
          const dt = JSON.parse(JSON.stringify(res.data));

          dt.forEach((ss:any) =>{
            
            if(ss.gridCategory === 'common'){
              this.models.common.title = ss && ss.title;
             
              this.models.common.headCode = ss && ss.headCode;
              this.models.common.endCode = ss && ss.endCode;
              this.models.common.gridCategory = ss && ss.gridCategory;
              this.models.common.id = ss && ss.id;
              const headObj = JSON.parse(this.models.common.headCode||"{}")
              if(headObj){
                Object.keys(headObj).forEach((k:any) =>{
                this.options.common.head.checkedValues.push(k);
              });
              }
              const endObj = JSON.parse(this.models.common.endCode||"{}")
              if(endObj ){
                Object.keys(endObj).forEach((k:any) =>{
                  this.options.common.end.checkedValues.push(k);
                })
              }
            }else{
     
              this.models.dynamic.titleDefineColumns = JSON.parse(ss.gridCategory);
              this.models.dynamic.titleDefine = this.extractProperty(this.models.dynamic.titleDefineColumns,"name").join('|');
              this.models.dynamic.title = ss && ss.title;
              this.models.dynamic.gridCategory = ss&& ss.gridCategory;
              this.models.dynamic.headCode = ss && ss.headCode;
              this.models.dynamic.endCode = ss && ss.endCode;
              this.models.dynamic.id = ss && ss.id;
      
              const headObj = JSON.parse(this.models.dynamic.headCode||"{}")
              if(headObj){
                Object.keys(headObj).forEach((k:any) =>{
                this.options.dynamic.head.checkedValues.push(k);
              });
              }
              const endObj = JSON.parse(this.models.dynamic.endCode||"{}")
              if(endObj ){
                Object.keys(endObj).forEach((k:any) =>{
                  this.options.dynamic.end.checkedValues.push(k);
                })
              }
            }
          });
        }
      }).catch((e) => {
        console.error(e);
      });
    }
  }

 extractProperty(objects: any, property: string): any {
  return objects.map((obj) => obj[property]);
 }

  commonHeadCodeHandlerCheckedChange(val:any){
    this.models.common.headCode = val;
  }

  commonEndCodeHandlerCheckedChange(val:any){
    this.models.common.endCode = val;
  }

  userDefineHeadCodeHandlerCheckedChange(val:any){
    this.models.dynamic.headCode = val;
  }

  userDefineEndCodeHandlerCheckedChange(val:any){
    this.models.dynamic.endCode = val;
  }

  commSubStructureHandler(val:any){
    this.models.common.commonDataList = JSON.parse(JSON.stringify(val));
    this.models.common.commonDataList = this.models.common.commonDataList.map(obj => {
      const { id, ...rest } = obj;
      return rest;
    });
  }

  dynamicSubStructureHandler(val:any){

    this.models.dynamic.dynamicDataList = JSON.parse(JSON.stringify(val));
    this.models.dynamic.dynamicDataList = this.models.dynamic.dynamicDataList.map(obj => {
      const { id, ...rest } = obj;
      return rest;
    });
  }

  handleTabsEdit(targetName, action) {
        if (action === 'add') {
          let idx = ++this.options.tab.tabIndex;
          let newTabName =  '自定义附表' + idx;
          this.options.tab.editableTabs.push({
            title: newTabName,
            name: newTabName,
            id: idx +''
          });
          this.options.tab.editableTabsValue = newTabName;
        }
        if (action === 'remove') {
          let tabs = this.options.tab.editableTabs;
          let activeName = this.options.tab.editableTabsValue;
          if(["标题信息","通用附表信息"].includes(activeName)){
            return;
          }
          if (activeName === targetName) {
            tabs.forEach((tab, index) => {
              if (tab.name === targetName) {
                let nextTab = tabs[index + 1] || tabs[index - 1];
                if (nextTab) {
                  activeName = nextTab.name;
                }
              }
            });
          }
          this.options.tab.editableTabsValue = activeName;
          this.options.tab.editableTabs = tabs.filter(tab => tab.name !== targetName);
        }
  }

  mounted(){
    //初始化加载类别选型
    this.buildCategoryData();
  }
}

</script>

<style scoped lang="scss">
  .greenFontColor{
    color: rgb(19, 206, 102);
  }
</style>

